import MSData
import WorkerMSAPI
import WorkerMSDB
import MSLogger
import MSDBTemplates
import WorkerSafeinside

import time
import os
import sys
import heartbeating
import pdb

#heartbeat = heartbeating.HeartbeatListener()
#heartbeat.start()

MSLogger.logInit('C:\\Magic\\safeinside.v1\\logs\\ms.safeinside_121.log', 2, True)
MSLogger.logInfo('ms driver started')
reader = WorkerMSDB.Worker('192.168.4.5', '52655', 'transferTest', 'sa', 'ms-004')
reader.connect()

#writer = WorkerPCNFirebird.Worker('192.168.0.120:C:\\pcn6\\data\\DATA.GDB', 'SYSDBA', 'masterkey')
writer = WorkerSafeinside.Worker('192.168.4.6', 11112)
#writer = WorkerSafeinside.Worker('77.221.134.106', 11112)
#writer.connect()
writer.connect()

def getObjectsFromDB(c, objs):
    objs_I1 = []

    MSDBTemplates.GET_MSObjects_FROM_CarOnline(reader.connection.cursor(), objs)
    f = open('objects_without_INPUT1.cfg', 'r')
    list_NI1 = []
    for s in f.readlines():
        s = s.strip()
        if len(s): list_NI1.append(s)
    for o in objs:
        if str(o.objectPCNId) in list_NI1:
            o.allowINPUT1 = False
            #MSLogger.logInfo('object %s:%s has NO i1' % (str(o.objectPCNId), str(o.objectMSId)))
        else:
            o.allowINPUT1 = True
            #MSLogger.logInfo('object %s:%s has i1' % (str(o.objectPCNId), str(o.objectMSId)))
        objs_I1.append(o)
    return objs_I1

#pdb.set_trace()
objects = getObjectsFromDB(reader.connection.cursor(), [])
ctr = 0

try:
    while True:
        try:
            if ctr == 6:
                objects = getObjectsFromDB(reader.connection.cursor(), objects)
                ctr = 0
            reader.readEventsPGSM(objects)
            reader.readEventsContactId(objects)
            reader.readEventsBolid(objects)
            reader.readEventsArgus(objects)
            #writer.writeEventsStatic(objects)
            writer.writeEventsStatic(objects)
            reader.finalyze(objects)
            ctr += 1
            time.sleep(1)
        except Exception, err:
            MSLogger.logError('ms driver processing error: %s' % (str(err)))
            time.sleep(3)
except KeyboardInterrupt:
    MSLogger.logError('ms daemon stopped')
    #heartbeat.stop()
    #os.unlink('C:\\safe\\ms.pid')
except Exception, err:
    shr = str(err)[0:100]
    MSLogger.logError('ms driver fatal error: %s' % (str(err)))
    #heartbeat.stop()
    #os.unlink('C:\\safe\\ms.pid')
